<?php

class Post extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @return CActiveRecord the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'wp_posts';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	
	
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('post_title, post_content', 'required'),
		);
	}
	

	/**
	 * @return array relational rules.
	 */
	
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'author' => array(self::BELONGS_TO, 'User', 'post_author'),
			'comments' => array(self::HAS_MANY, 'Comment', 'comment_post_ID', 'condition'=>'comment_approved=1', 'order'=>'comments.comment_date DESC'),
			'commentCount' => array(self::STAT, 'Comment', 'comment_post_ID', 'condition'=>'comment_approved=1'),
		);
	}

	public function getUrl(){
		return Yii::app()->createUrl('post/view', array(
			'id'=>$this->ID,
		));
	}
	
	public function getEditUrl(){
		return Yii::app()->createUrl('post/update', array(
				'id'=>$this->ID,
		));
	}
	
	public function getDeleteUrl(){
		return Yii::app()->createUrl('post/delete', array(
				'id'=>$this->ID,
		));
	}
	
	public function deletePostAndComments(){
		$this->delete();
		$this->deleteComments();
	}
	
	public function deleteComments(){
		foreach($this->comments as $comment){
			$comment->delete();
		}
	}
	
	protected function beforeSave()
	{
		if(parent::beforeSave()){
			if($this->isNewRecord)
				$this->post_date = date("Y-m-d H:i:s");
			$this->post_modified = date("Y-m-d H:i:s");
			return true;
		}
		else
			return false;
	}
	/**
	 * Adds a new comment to this post.
	 * This method will set status and post_id of the comment accordingly.
	 * @param Comment the comment to be added
	 * @return boolean whether the comment is saved successfully
	 */
	public function addComment($comment)
	{
		if(Yii::app()->params['commentNeedApproval'])
			$comment->comment_approved=0;
		else;
			$comment->comment_approved=1;
		$comment->comment_post_ID=$this->ID;
		$comment->comment_date=date("Y-m-d H:i:s");
		return $comment->save();
		
	}

	
}